package com.vogue.supplymall.admin.business.common;

import com.qingstor.sdk.exception.QSException;
import com.vogue.supplymall.common.constant.ConstantBean;
import com.vogue.supplymall.common.domain.dto.admin.PrivatePlatformAppInfo;
import com.vogue.supplymall.common.exception.RemoveUploadException;
import com.vogue.supplymall.common.exception.UploadException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import qingstor.util.QingstorService;

import java.io.IOException;
import java.io.InputStream;

/**
 * The type Upload resource utils.
 *
 * @author zhangliang
 * Create in 2018-07-16
 */
@Service("uploadResourceUtils")
public class UploadResourceUtils {
    public static final Logger LOGGER_UPLOADRESOURCEUTILS = LoggerFactory.getLogger(UploadResourceUtils.class);

    /**
     * Upload resource string.
     *
     * @param appInfo the app info
     * @return the string
     */
    public String uploadResource(PrivatePlatformAppInfo appInfo) {
        CommonsMultipartFile file = appInfo.getFile();
        if (file.getSize() == 0) {
            throw new UploadException("文件内容为空，请重新选择文件！");
        }
        String type = "";
        if (appInfo.getType() == 2) {
            type = "/android";
        } else {
            type = "/ios";
        }
        String logicalUrl = "/" + ConstantBean.SYSTEM_NAME
                + "/" + "app"
                + type
                + "/" + appInfo.getName()
                + "/" + appInfo.getFilename() + "." + appInfo.getExtension();

        String url = QingstorService.getUrl() + logicalUrl;
        removeResource(url);
        try {
            InputStream inputStream = file.getInputStream();
            QingstorService.putFileInputStream(logicalUrl, inputStream);
        } catch (QSException e) {
            LOGGER_UPLOADRESOURCEUTILS.error(">>> 上传文件失败 QSException");
            throw new UploadException("");
        } catch (IOException e) {
            LOGGER_UPLOADRESOURCEUTILS.error(">>> 上传文件失败 IOException");
            throw new UploadException("");
        }
        LOGGER_UPLOADRESOURCEUTILS.info(">>> 上传文件 " + url);
        return url.replaceAll("\\\\", "/");
    }

    /**
     * @param appInfo appInfo
     * @return String
     */
    public String uploadResourceWithInputstream(PrivatePlatformAppInfo appInfo) {
        CommonsMultipartFile file = appInfo.getFile();
        if (file.getSize() == 0) {
            throw new UploadException("文件内容为空，请重新选择文件！");
        }
        String type = "";
        if (appInfo.getType() == 2) {
            type = "/android";
        } else {
            type = "/ios";
        }
        String logicalUrl = "/" + ConstantBean.SYSTEM_NAME
                + "/" + "app"
                + type
                + "/" + appInfo.getName()
                + "/" + appInfo.getFilename() + "." + appInfo.getExtension();

        String url = QingstorService.getUrl() + logicalUrl;
        removeResource(url);
        try {
            InputStream inputStream = appInfo.getFileStream();
            QingstorService.putFileInputStream(logicalUrl, inputStream);
        } catch (QSException e) {
            LOGGER_UPLOADRESOURCEUTILS.error(">>> 上传文件失败 QSException");
            throw new UploadException("");
        } catch (Exception e) {
            LOGGER_UPLOADRESOURCEUTILS.error(">>> 上传文件失败 IOException");
            throw new UploadException("");
        }
        LOGGER_UPLOADRESOURCEUTILS.info(">>> 上传文件 " + url);
        return url.replaceAll("\\\\", "/");
    }

    /**
     * @param url url
     * @return Boolean
     */
    private Boolean removeResource(String url) {
        if (url == null || url.length() == 0) {
            return true;
        }
        LOGGER_UPLOADRESOURCEUTILS.info(">>> 删除上传文件 " + url);
        try {
            url = formatUrl(url);
            QingstorService.deleteFile(url);
        } catch (QSException e) {
            LOGGER_UPLOADRESOURCEUTILS.error(">>> 删除文件失败 QSException" + e.toString());
            throw new RemoveUploadException("");
        } catch (Exception ex) {
            LOGGER_UPLOADRESOURCEUTILS.error(">>> 上传文件前删除指定待删除文件异常" + ex.toString());
            throw new RemoveUploadException("");
        }
        return true;
    }

    /**
     * 将给的路径转化成可操作的路径格式
     *
     * @param url url
     * @return String
     */
    private String formatUrl(String url) {
        if (url.startsWith("https")) {
            if (QingstorService.getUrl().startsWith("https")) {
                url = url.replace(QingstorService.getUrl(), "");
            } else if (QingstorService.getUrl().startsWith("http")) {
                url = url.replace(QingstorService.getUrl().replaceAll("http", "https"), "");
            }
        } else if (url.startsWith("http")) {
            if (QingstorService.getUrl().startsWith("https")) {
                url = url.replace(QingstorService.getUrl().replaceAll("https", "http"), "");
            } else if (QingstorService.getUrl().startsWith("http")) {
                url = url.replace(QingstorService.getUrl(), "");
            }
        }
        if (url.indexOf("\\") > -1) {
            url = url.replaceAll("\\\\", "/");
        }
        return url;
    }
}
